//
//  HQActivityController.swift
//  TodayNews
//
//  Created by 郝庆 on 16/8/22.
//  Copyright © 2016年 haoqing. All rights reserved.
//

import UIKit

class HQActivityController: UIViewController {
    
    // 请求url
    let urlString = BASE_URL + "2/wap/activity/?iid=5124013949"
    
    @IBOutlet weak var webView: UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 设置UI
        setupUI()
        
    }
    
    /// 设置UI
    private func setupUI() {
        
        title = "活动"
        navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "new_more_titlebar_28x28_"), style: .Plain, target: self, action: #selector(moreButtonClicked))
        
        // 加载网页
        let url = NSURL(string: urlString)
        webView.loadRequest(NSURLRequest(URL: url!))
        
        // 自动对页面进行缩放以适应屏幕
        webView.scalesPageToFit = true
        webView.dataDetectorTypes = .All
    }
    
    
    /// 点击活动界面更多按钮
    @objc private func moreButtonClicked() {
        
        let alertVc = UIAlertController(title: "非Wifi网络流量", message: nil, preferredStyle: .ActionSheet)
        
        let refreshAction = UIAlertAction(title: "刷新", style: .Default) { (_) in
            self.webView.reload()
        }
        
        let copyLinkAction = UIAlertAction(title: "复制链接", style: .Default) { (_) in
            // 复制到剪贴板
            let pasteboard = UIPasteboard.generalPasteboard()
            pasteboard.string = self.urlString
        }
        
        let safariAction = UIAlertAction(title: "使用Safari打开", style: .Default) { (_) in
            
            let url = NSURL(string: self.urlString)
            
            if UIApplication.sharedApplication().canOpenURL(url!) {
                
                UIApplication.sharedApplication().openURL(url!)
            }
        }
        
        let cancleAction = UIAlertAction(title: "取消", style: .Cancel, handler: nil)
        
        
        alertVc.addAction(refreshAction)
        alertVc.addAction(copyLinkAction)
        alertVc.addAction(safariAction)
        alertVc.addAction(cancleAction)
        
        presentViewController(alertVc, animated: true, completion: nil)
    }
}

extension HQActivityController: UIWebViewDelegate {
    func webViewDidStartLoad(webView: UIWebView) {
        UIApplication.sharedApplication().networkActivityIndicatorVisible = true
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        UIApplication.sharedApplication().networkActivityIndicatorVisible = false
    }
}
